﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

using NativeWifi;
using Model;
using Utility;

namespace WifiScannTest
{
    public partial class frm_Main : Form
    {
        private WifiHelper m_WifiHelper;

        public frm_Main()
        {
            InitializeComponent();
        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
            m_WifiHelper = new WifiHelper();  //加载wifi

            this.WifiListView.Items.Clear();
            SetwifiList();
            wifiList_AddItem(null, null);

            System.Timers.Timer t = new System.Timers.Timer(12000);   //实例化Timer类，设置间隔时间为10000毫秒；   
            t.Elapsed += new System.Timers.ElapsedEventHandler(wifiList_AddItem); //到达时间的时候执行事件；   
            t.AutoReset = true;   //设置是执行一次（false）还是一直执行(true)；   
            t.Enabled = true;     //是否执行System.Timers.Timer.Elapsed事件；
        }



        #region listview
        /// <summary>
        /// 设置listview
        /// </summary>
        private void SetwifiList()
        {
            this.WifiListView.Columns.Add("SSID", 240, HorizontalAlignment.Left);
            this.WifiListView.Columns.Add("Cipher", 180, HorizontalAlignment.Left);
            this.WifiListView.Columns.Add("Authentication", 180, HorizontalAlignment.Left);
            this.WifiListView.Columns.Add("SignalQuality", 160, HorizontalAlignment.Left);
            this.WifiListView.Columns.Add("RSSI", 160, HorizontalAlignment.Left);

            //ColumnHeader ch = new ColumnHeader();  //先创建列表头
            WifiListView.GridLines = true;//显示网格
            WifiListView.Scrollable = true;//显示所有项时是否显示滚动条
            WifiListView.AllowColumnReorder = true;
            WifiListView.FullRowSelect = true;
            WifiListView.CheckBoxes = false;
        }
        #endregion

        #region 添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        private void wifiList_AddItem(object source, System.Timers.ElapsedEventArgs e)
        {
            if (this.IsHandleCreated)
            {
                this.lblInfo.Invoke(new EventHandler(delegate
                {
                    string strResult = "";

                    strResult = m_WifiHelper.GetCurrentConnection();
                    lblInfo.Text = "当前连接的SSID：" + strResult ;
                    Image img = new Bitmap(Environment.CurrentDirectory + "/image/green.png");
                    picWifi.BackgroundImage = img;
                }));
                this.WifiListView.Invoke(new EventHandler(delegate
                {
                    this.WifiListView.Items.Clear();
                    this.WifiListView.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度  

                    List<WIFISSID> wifiList = new List<WIFISSID>();
                    wifiList = m_WifiHelper.ScanSSID();

                    int nCount = wifiList.Count;
                    lblApCount.Text = nCount.ToString();
                    for (int i = 0; i < nCount; i++)
                    {
                        WIFISSID wifissid = wifiList[i];

                        ListViewItem wifiitem = WifiListView.Items.Add(wifissid.SSID);
                        wifiitem.SubItems.Add(wifissid.dot11DefaultCipherAlgorithm);
                        wifiitem.SubItems.Add(wifissid.dot11DefaultAuthAlgorithm);
                        wifiitem.SubItems.Add(wifissid.wlanSignalQuality + "");
                        wifiitem.SubItems.Add(wifissid.RSSI + "");

                    }

                    this.WifiListView.EndUpdate();  //结束数据处理，UI界面一次性绘制。
                    this.WifiListView.View = System.Windows.Forms.View.Details;
                }));


            }
        }
        #endregion

        private void WifiListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool bFlag = false;
            if (WifiListView.SelectedIndices != null && WifiListView.SelectedItems.Count > 0)
            {
                string stSSID = "";
                ListView.SelectedIndexCollection c = WifiListView.SelectedIndices;
                MessageBoxButtons messButton = MessageBoxButtons.OKCancel;

                stSSID = WifiListView.Items[c[0]].Text.Trim();

                DialogResult dr = MessageBox.Show("确定要连接" + stSSID + "吗?", "wifi连接", messButton);
                if (dr == DialogResult.OK)//如果点击“确定”按钮
                {
                    string strResult = "";

                    strResult = m_WifiHelper.GetCurrentConnection();
                    if (strResult.Equals(stSSID))
                    {
                        lblInfo.Text = "SSID：" + stSSID + " 已经连接，不需要重复";
                        lblInfo.ForeColor = Color.Black;
                        lblInfo.BackColor = Color.LightGreen;

                        return;
                    }

                    frm_WifiPasswd frmWifiPasswd = new frm_WifiPasswd();
                    frmWifiPasswd.ShowDialog();

                    string strWifiPasswd = "";
                    strWifiPasswd = frmWifiPasswd.m_strWifiPasswd;
                    List<WIFISSID> wifiList = new List<WIFISSID>();
                    wifiList = m_WifiHelper.ScanSSID();

                    int nCount = wifiList.Count;
                    for (int i = 0; i < nCount; i++)
                    {
                        WIFISSID wifissid = wifiList[i];
                        if (wifissid.SSID.Equals(stSSID))
                        {

                            bFlag = m_WifiHelper.ConnectToSSID(wifissid, strWifiPasswd);
                            if (!bFlag)
                            {
                                lblInfo.Text = "连接SSID：" + stSSID + " 失败";
                                lblInfo.ForeColor = Color.White;
                                lblInfo.BackColor = Color.Red;

                            }
                            else
                            {
                                lblInfo.Text = "连接SSID：" + stSSID + " 成功";
                                lblInfo.ForeColor = Color.Black;
                                lblInfo.BackColor = Color.LightGreen;
                            }
                        }
                    }//end for
                }
            }
        }//end WifiListView_SelectedIndexChanged
    }
}